package com.sdy.approval.provider;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.approval.biz.model.TpConfigOld;
import com.sdy.approval.biz.param.AddApprovalsParam;
import com.sdy.approval.biz.service.TpConfigOldService;
import com.sdy.approval.biz.utils.RSAEncrypt;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.usercenter.api.dto.DeptDto;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.approval.biz.model.TpApproveFlow;
import com.sdy.approval.biz.model.TpApproveFlowConfig;
import com.sdy.approval.biz.model.TpOrder;
import com.sdy.approval.biz.service.TpApproveFlowConfigService;
import com.sdy.approval.biz.service.TpApproveFlowService;
import com.sdy.approval.biz.service.TpOrderService;
import com.sdy.common.model.Response;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.annotation.RemoteService;
import com.sdy.usercenter.api.UserQueryApi;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

/**
 * <p>
 * RPC调用
 * </p>
 *
 * @author cgj
 */
@Slf4j
@RemoteService
public class TpResProvider implements ApprovalAllApi {

    @Autowired
    private TpOrderService tpOrderService;
    @Autowired
    private TpApproveFlowConfigService tpApproveFlowConfigService;
    @Autowired
    private TpApproveFlowService tpApproveFlowService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private TpConfigOldService tpConfigOldService;
    @Value("${res.app.secret}")
    private String msg;

    /**
     * 外部申请入口
     *
     * @param list(放入[order_item_no,res_id,user_id]) order_item_no订单号, res_id:E("[查询平台]22"), user_id人员id
     * @return Integer
     */
    @Override
    public Integer lookResId(List<Map<String, Object>> list) throws BizException {
        // 只能被需要的数据
        Date date = new Date();
        if (list.size() == 1) {
            String orderNo = (String) list.get(0).get("order_item_no");
            String resId = (String) list.get(0).get("res_id");
            LambdaQueryWrapper<TpApproveFlowConfig> lqwtacs = new LambdaQueryWrapper<>();
            lqwtacs.eq(TpApproveFlowConfig::getResId, resId);
            TpApproveFlowConfig tpApproveFlowConfig = tpApproveFlowConfigService.getOne(lqwtacs);
            if (tpApproveFlowConfig == null) {
                log.info("对不起，请先配置流程模板！");
                return -2;
            }
            Integer userId = (Integer) list.get(0).get("user_id");
            TpOrder tpOrder = new TpOrder();
            tpOrder.setApplicationNum(orderNo)
                    .setResId(resId)
                    .setGsOrderState(3)
                    .setOrderAvailable(1)
                    .setApplyTime(date);
            Boolean tpOrderSava = tpOrderService.save(tpOrder);
            if (!tpOrderSava) {
                return -1;
            }
            // updateApprovalNotToYes(-1该订单数据异常  -2提交失败  -3节点生成失败)
            Integer updateApprovalNotToYes = updateApprovalNotToYes(orderNo, userId, 1, date);
            if (updateApprovalNotToYes == -1) {
                return -1;
            } else if (updateApprovalNotToYes == -2) {
                return -2;
            } else if (updateApprovalNotToYes == -3) {
                return -3;
            }
        } else {
            List<String> applicationNumList = new ArrayList<>();
            List<String> resIdList = new ArrayList<>();
            List<Integer> userIdList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                String orderNo = (String) list.get(i).get("order_item_no");
                applicationNumList.add(orderNo);
                String resId = (String) list.get(i).get("res_id");
                resIdList.add(resId);
                Integer userId = (Integer) list.get(i).get("user_id");
                userIdList.add(userId);
                TpOrder tpOrder = new TpOrder();
                tpOrder.setApplicationNum(orderNo)
                        .setResId(resId)
                        .setGsOrderState(3)
                        .setOrderAvailable(1)
                        .setApplyTime(new Date());
                Boolean tpOrderSava = tpOrderService.save(tpOrder);
                if (!tpOrderSava) {
                    log.info("多条中,存在生成云订错误的情况!");
                    return -1;
                }
            }
            // updateApprovalNotToYesMany(-1多条订单中，存在订单异常  -2存在申请的资源未配置流程! -3多条中,存在生成第一节点失败的数据!)
            Integer updateApprovalNotToYesMany = updateApprovalNotToYesMany(applicationNumList, resIdList, userIdList);
            if (updateApprovalNotToYesMany == -1) {
                return -1;
            } else if (updateApprovalNotToYesMany == -2) {
                return -2;
            } else if (updateApprovalNotToYesMany == -3) {
                return -3;
            }
        }
        return 1;
    }

    /**
     * 通过资源id查询流程配置
     *
     * @param resId 资源id (E：resId = "[资源目录]37")
     * @return
     */
    @Override
    public List<TpApproveFlowConfig> selectApprovalByResId(String resId) {
        List<TpApproveFlowConfig> list = tpApproveFlowConfigService.list(Wrappers.<TpApproveFlowConfig>lambdaQuery()
                .eq(TpApproveFlowConfig::getResId, resId));
        return list;
    }

    /**
     * 根据订单号查询当前订单
     *
     * @param applyNum 订单号
     * @return
     */
    @Override
    public List<TpOrder> selectOrderByApplyNum(String applyNum, Integer orderAvailable) {
        List<TpOrder> orders = tpOrderService.list(Wrappers.<TpOrder>lambdaQuery()
                .eq(TpOrder::getApplicationNum, applyNum)
                .eq(orderAvailable != null, TpOrder::getOrderAvailable, orderAvailable));
        return orders;
    }

    /**
     * 修改订单时删除冗余数据(删除生成的流程节点,删除云订单)
     *
     * @param applyNum 订单号
     * @return
     */
    @Override
    public Integer delOrderAndFlowsByApplyNum(String applyNum, Integer userId) throws BizException {
        // 准备数据
        Date date = new Date();
        // 1.删除原订单和流程
        // 删除tp_approve_flow里的数据
        List<TpApproveFlow> flows = tpApproveFlowService.list(Wrappers.<TpApproveFlow>lambdaQuery()
                .eq(TpApproveFlow::getApplyId, applyNum)
                .eq(TpApproveFlow::getFlowAvailable, 1));
        List<Integer> flowIds = flows.stream().map(TpApproveFlow::getId).collect(Collectors.toList());
        boolean b = tpApproveFlowService.removeByIds(flowIds);
        if (!b) {
            log.info("删除流程数据时出错");
            return -4;
        }

        // 删除TpOrder里的数据
        LambdaQueryWrapper<TpOrder> selectOrder = new LambdaQueryWrapper<>();
        selectOrder.eq(TpOrder::getApplicationNum, applyNum)
                .eq(TpOrder::getOrderAvailable, 1);
        TpOrder order = tpOrderService.getOne(selectOrder);
        boolean remove = tpOrderService.remove(selectOrder);
        if (!remove) {
            log.info("删除流程数据时出错");
            return -5;
        }

        // 2.重新生成TpOrder
        TpOrder tpOrder = new TpOrder();
        tpOrder.setApplicationNum(applyNum)
                .setResId(order.getResId())
                .setGsOrderState(3)
                .setOrderAvailable(1)
                .setApplyTime(date)
                .setModifyTime(date);
        Boolean tpOrderSave = tpOrderService.save(tpOrder);
        if (!tpOrderSave) {
            log.info("重新生成TpOrder信息失败");
            return -6;
        }

        // 3.重新生成第一节点
        // updateApprovalNotToYes(-1该订单数据异常  -2提交失败  -3节点生成失败)
        Integer updateApprovalNotToYes = updateApprovalNotToYes(applyNum, userId, 2, date);
        if (updateApprovalNotToYes == -1) {
            return -1;
        } else if (updateApprovalNotToYes == -2) {
            return -2;
        } else if (updateApprovalNotToYes == -3) {
            return -3;
        }
        log.info("修改成功，并重新生成第一节点");
        return 1;
    }

    /**
     * 根据订单号查询所有流程（历史版本 and 最新版本）
     *
     * @param applicationNum 订单号
     * @return
     */
    @Override
    public List<TpApproveFlow> selectApprovalFlowByResId(String applicationNum) {
        LambdaQueryWrapper<TpApproveFlow> lqwtaf = new LambdaQueryWrapper<>();
        lqwtaf.eq(TpApproveFlow::getApplyId, applicationNum);
        List<TpApproveFlow> tpApproveFlows = tpApproveFlowService.list(lqwtaf);
        for (int i = 0; i < tpApproveFlows.size(); i++) {
            if (tpApproveFlows.get(i).getOperType() == null) {
                tpApproveFlows.get(i).setDeptName(userQueryApi.getDept(tpApproveFlows.get(i).getApprovalDeptId()).getName());
                if (tpApproveFlows.get(i).getModifyUser() != null) {
                    tpApproveFlows.get(i).setApprovalName(userQueryApi.getUser(tpApproveFlows.get(i).getModifyUser()).getName());
                }
            } else if (tpApproveFlows.get(i).getOperType() != null) {
                tpApproveFlows.get(i).setApprovalName(userQueryApi.getUser(tpApproveFlows.get(i).getUserId()).getName());
                tpApproveFlows.get(i).setDeptName(userQueryApi.getUser(tpApproveFlows.get(i).getUserId()).getOwnDeptName());
            }
        }
        return tpApproveFlows;
    }

    /**
     * 根据订单号查询当前用户的审批流程（排除废除流程）
     *
     * @param applicationNum 订单号
     * @param deptIdList     登陆人员的部门id列表
     * @param roldIdList     登陆人员的角色id列表
     * @return
     */
    @Override
    public TpApproveFlow selectApprovalFlowResultByResId(String applicationNum, List<Integer> deptIdList, List<Integer> roldIdList) {
        LambdaQueryWrapper<TpApproveFlow> lqwtaf = new LambdaQueryWrapper<>();
        lqwtaf.eq(TpApproveFlow::getApplyId, applicationNum)
                .in(TpApproveFlow::getApprovalDeptId, deptIdList)
                .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                .eq(TpApproveFlow::getFlowAvailable, 1);
        TpApproveFlow tpApproveFlow = tpApproveFlowService.getOne(lqwtaf);
        return tpApproveFlow;
    }

    /**
     * 根据订单号查询当前用户的审批流程(批量)
     *
     * @param applyIdList 订单号
     * @param deptIdList  登陆人员的部门id列表
     * @param roleIdList  登陆人员的角色id列表
     * @return
     */
    @Override
    public List<TpApproveFlow> selectApprovalFlowByNumOrderList(List<String> applyIdList, List<Integer> deptIdList, List<Integer> roleIdList) {
        LambdaQueryWrapper<TpApproveFlow> lqwtaf = new LambdaQueryWrapper<>();
        lqwtaf.in(TpApproveFlow::getApplyId, applyIdList)
                .in(TpApproveFlow::getApprovalDeptId, deptIdList)
                .in(TpApproveFlow::getApprovalRoleId, roleIdList)
                .eq(TpApproveFlow::getFlowAvailable, 1);
        List<TpApproveFlow> tpApproveFlow = tpApproveFlowService.list(lqwtaf);
        return tpApproveFlow;
    }

    /**
     * 根据订单号查询当前用户的审批流程(实施工单查询专供)废除的流程节点信息也带出
     *
     * @param applyIdList 订单号
     * @param deptIdList  登陆人员的部门id列表
     * @param roleIdList  登陆人员的角色id列表
     * @return
     */
    @Override
    public List<TpApproveFlow> selectApprovalFlowByNumToDir(List<String> applyIdList, List<Integer> deptIdList, List<Integer> roleIdList) {
        LambdaQueryWrapper<TpApproveFlow> lqwtaf = new LambdaQueryWrapper<>();
        lqwtaf.in(TpApproveFlow::getApplyId, applyIdList)
                .in(TpApproveFlow::getApprovalDeptId, deptIdList)
                .in(TpApproveFlow::getApprovalRoleId, roleIdList);
        List<TpApproveFlow> tpApproveFlow = tpApproveFlowService.list(lqwtaf);
        return tpApproveFlow;
    }

    /**
     * 流程体系新建（即新建流程配置）
     *
     * @param auditDepartmentId 配置节点所需部门id
     * @param auditRoleId       配置节点所需角色id
     * @param prefix            平台前缀，如：查询平台
     * @param rId               该平台的资源id；资源主键
     * @return
     * @throws Exception
     */
    @Override
    public String insertApproval(List<Integer> auditDepartmentId, List<Integer> auditRoleId, String prefix, String rId) throws Exception {
        // 判断是否有正在审批的流程记录（有则无法覆盖，没有则直接覆盖）
        String resId = prefix + rId;
        boolean remove = tpApproveFlowConfigService.remove(Wrappers.<TpApproveFlowConfig>lambdaQuery()
                .eq(TpApproveFlowConfig::getResId, resId));
        Assert.notTrue(remove, "移除配置失败");
        //}

        if (auditDepartmentId == null || auditRoleId == null) {
            log.info("请输入正常的参数");
            return "请输入正常的参数";
        }
        int dep = auditDepartmentId.size();
        int role = auditRoleId.size();
        if (dep > role) {
            log.info("缺失部门的对应角色");
            return "缺失部门的对应角色";
        } else if (dep < role) {
            log.info("缺失角色的对应部门");
            return "缺失角色的对应部门";
        }
        // 得到数据库当前最大的流程id
        Integer maxFlowId = tpApproveFlowConfigService.getMaxFlowId();
        if (maxFlowId == null) {
            maxFlowId = 0;
        }
        if (auditDepartmentId != null && dep >= 1) {
            // 优化
            for (int i = 1; i <= dep; i++) {
                TpApproveFlowConfig tpApproveFlowConfig = new TpApproveFlowConfig();
                // 新增配置模板
                tpApproveFlowConfig.setFlowId(maxFlowId + 1).setResId(resId).setCurrentFlowLink(i)
                        .setAuditDepartmentId(auditDepartmentId.get(i - 1)).setAuditRoleId(auditRoleId.get(i - 1))
                        .setNextFlowNode((i + 1) > dep ? null : (i + 1)).setCreateTime(new Date());
                Boolean a = tpApproveFlowConfigService.save(tpApproveFlowConfig);
                if (a != true) {
                    log.info("第" + i + "【审批节点】信息增加失败");
                    return "第" + i + "【审批节点】信息增加失败";
                }
            }
        }
        log.info("流程生成成功");
        return "流程生成成功";
    }

    /**
     * 删除流程的配置信息
     *
     * @param prefix 前缀 E:查询平台
     * @param rId    资源id(主键)
     * @return
     */
    @Override
    public Boolean deleteFlowConfig(String prefix, Integer rId) {
        // 判断是否有正在审批的流程记录（有则无法覆盖，没有则直接覆盖）
        String resId = prefix + rId;
        // 检查是否存在未审批的正在进行的流程（又得话则不可删除）
        LambdaQueryWrapper<TpApproveFlow> lqwtaf = new LambdaQueryWrapper<>();
        lqwtaf.eq(TpApproveFlow::getResId, resId)
                .eq(TpApproveFlow::getFlowAvailable, 1)
                .eq(TpApproveFlow::getResult, 1);
        List<TpApproveFlow> tafList = tpApproveFlowService.list(lqwtaf);
        if (tafList.size() > 1) {
            log.info("存在进行中的流程，不可删除该流程配置信息");
            return false;
        }
        // 删除配置流程信息
        LambdaQueryWrapper<TpApproveFlowConfig> lqwtafc = new LambdaQueryWrapper<>();
        lqwtafc.eq(TpApproveFlowConfig::getResId, resId);
        Boolean i = tpApproveFlowConfigService.remove(lqwtafc);
        if (!i) {
            log.info("配置流程信息删除失败");
            return false;
        }
        return true;
    }

    /**
     * 我的订阅申请表单详情(未提交)
     *
     * @return
     */
    @Override
    public List<TpOrder> selectAllTpResOrderListNotSubmitted() {
        return tpOrderService.selectAllTpOrderListNotSubmit();
    }

    /**
     * 流程修改(用于申请单修改)
     *
     * @param applicationNum 修改的订单号
     * @param userId         修改人的id
     * @return
     */
    @Override
    public Boolean updateFlow(String applicationNum, Integer userId) throws BizException {
        // 准备需要的数据
        Date date = new Date();
        // 1.先废除原先的数据
        // 废除tp_approve_flow里的数据
        LambdaUpdateWrapper<TpApproveFlow> lambdaUpdateWrapper = new LambdaUpdateWrapper<TpApproveFlow>();
        lambdaUpdateWrapper.eq(TpApproveFlow::getApplyId, applicationNum)
                .eq(TpApproveFlow::getFlowAvailable, 1)
                .set(TpApproveFlow::getFlowAvailable, 2);
        Boolean tpApproveFlowU = tpApproveFlowService.update(lambdaUpdateWrapper);
        // 废除TpOrder里的数据
        // 废除之前先查出数据
        LambdaQueryWrapper<TpOrder> lqwta = new LambdaQueryWrapper<>();
        lqwta.eq(TpOrder::getApplicationNum, applicationNum)
                .eq(TpOrder::getOrderAvailable, 1);
        TpOrder t = tpOrderService.getOne(lqwta);
        String resId = t.getResId();
        LambdaUpdateWrapper<TpOrder> luwto = new LambdaUpdateWrapper<>();
        luwto.eq(TpOrder::getApplicationNum, applicationNum)
                .eq(TpOrder::getOrderAvailable, 1)
                .set(TpOrder::getModifyTime, date)
                .set(TpOrder::getModifyUser, userId)
                .set(TpOrder::getOrderAvailable, 2);
        Boolean tpOrderU = tpOrderService.update(luwto);
        if (!tpApproveFlowU || !tpOrderU) {
            log.info("废除流程或者订单时出错");
            return false;
        }
        // 2.重新生成TpOrder
        TpOrder tpOrder = new TpOrder();
        tpOrder.setApplicationNum(applicationNum)
                .setResId(resId)
                .setGsOrderState(3)
                .setOrderAvailable(1)
                .setApplyTime(date)
                .setModifyTime(date);
        Boolean tpOrderSava = tpOrderService.save(tpOrder);
        if (!tpOrderSava) {
            log.info("重新生成TpOrder信息失败");
            return false;
        }
        // 3.重新生成第一节点
        // updateApprovalNotToYes(-1该订单数据异常  -2提交失败  -3节点生成失败)
        Integer updateApprovalNotToYes = updateApprovalNotToYes(applicationNum, userId, 2, date);
        if (updateApprovalNotToYes != 1) {
            return false;
        }
        log.info("修改成功，并重新生成第一节点");
        return true;
    }

    /**
     * 我的订阅申请表单详情(单条，详情，点击申请单号查看，审批明细TpApproveFlow)
     *
     * @param application_num 击数据传入TpOrder内的申请单号
     * @return
     */
    @Override
    public Response<List<TpApproveFlow>> selectApprovalDeilByApplicationNum(String application_num) {
        LambdaQueryWrapper<TpApproveFlow> wrapper = new LambdaQueryWrapper<>();
        // 根据申请单号查询详情
        wrapper.eq(StringUtil.isNotBlank(application_num), TpApproveFlow::getApplyId, application_num)
                .eq(TpApproveFlow::getFlowAvailable, 1);
        List<TpApproveFlow> tpApproveFlow = tpApproveFlowService.list(wrapper);
        return Response.success(tpApproveFlow);
    }

    /**
     * 单条申请
     *
     * @param applicationNum 提交申请时传入申请单号
     * @param userId         提交人的id
     * @return
     */
    @Override
    public Integer updateApprovalNotToYes(String applicationNum, Integer userId, Integer operType, Date date) throws BizException {
        // 查询该订单
        LambdaQueryWrapper<TpOrder> lqwto = new LambdaQueryWrapper<>();
        lqwto.eq(TpOrder::getApplicationNum, applicationNum).eq(TpOrder::getOrderAvailable, 1);
        TpOrder order = tpOrderService.getOne(lqwto);
        if (order == null) {
            log.info("云订单异常");
            return -1;
        }
        String resId = order.getResId();
        List<TpApproveFlowConfig> tafcs;
        if (resId.contains("[事项录入]")) {
            tafcs = tpApproveFlowConfigService.selectTpApproveFlowConfig("[事项录入]");
        } else {
            // 获得该资源的流程配置数据
            tafcs = tpApproveFlowConfigService.selectTpApproveFlowConfig(resId);
        }
        // 生成操作节点
        Boolean addSubNode = tpApproveFlowService.addSubNode(applicationNum, userId, operType, date, resId);
        Assert.notTrue(addSubNode, "新增提交操作节点时失败");
        // 获得第一审批节点的部门和角色id
        int auditDepartmentId = tafcs.get(0).getAuditDepartmentId();
        int auditRoleId = tafcs.get(0).getAuditRoleId();
        TpApproveFlow tpApproveFlow = new TpApproveFlow();
        tpApproveFlow.setApplyId(applicationNum)
                .setApprovalDeptId(auditDepartmentId)
                .setApprovalRoleId(auditRoleId)
                .setResId(resId)
                .setResult(1)
                .setFlowAvailable(1)
                .setCreateTime(new Date())
                .setCurrentFlowLink(tafcs.get(0).getCurrentFlowLink())
                .setNextFlowLink(tafcs.get(0).getNextFlowNode())
                .setUserId(userId);
        Boolean tafsSave = tpApproveFlowService.save(tpApproveFlow);
        if (!tafsSave) {
            log.info("节点生成失败");
            return -3;
        }
        log.info("提交申请成功，并成功生成第一节点");
        return 1;
    }

    /**
     * 我的订阅申请表单(状态【未提交转提交】多条)
     *
     * @param applicationNumList 提交时传入的申请单号集合
     * @param resIdList          资源id
     * @param userIdList         人员id
     * @return
     */
    @Override
    public Integer updateApprovalNotToYesMany(List<String> applicationNumList, List<String> resIdList, List<Integer> userIdList) throws BizException {
        // 查询该订单
        LambdaQueryWrapper<TpOrder> lqwto = new LambdaQueryWrapper<>();
        lqwto.in(TpOrder::getApplicationNum, applicationNumList)
                .eq(TpOrder::getOrderAvailable, 1);
        List<TpOrder> orderList = tpOrderService.list(lqwto);
        for (int i = 0; i < orderList.size(); i++) {
            if (orderList.get(i) == null) {
                log.info("多条订单中，存在订单异常");
                return -1;
            }
        }
        // 获取每个resId的第一审批节点配置
        LambdaQueryWrapper<TpApproveFlowConfig> lqwtaf = new LambdaQueryWrapper<>();
        lqwtaf.eq(TpApproveFlowConfig::getCurrentFlowLink, 1)
                .in(TpApproveFlowConfig::getResId, resIdList);
        List<TpApproveFlowConfig> list = tpApproveFlowConfigService.list(lqwtaf);
        // 判断每个资源id是否都已经配置了流程
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == null) {
                log.info("多条中存在未配置流程的资源!");
                return -2;
            }
        }

        Map<String, TpApproveFlowConfig> configMap = new HashMap<>();
        for (TpApproveFlowConfig config : list) {
            configMap.put(config.getResId(), config);
        }
        log.info("configMap--" + configMap);
        // 生成每个订单的操作节点
        List<AddApprovalsParam> addApprovalsParams = new ArrayList<>();
        for (int i = 0; i < applicationNumList.size(); i++) {
            AddApprovalsParam addApprovalsParam = new AddApprovalsParam();
            addApprovalsParam.setApplyNum(applicationNumList.get(i))
                    .setUserId(userIdList.get(i)).setResId(resIdList.get(i));
            addApprovalsParams.add(addApprovalsParam);
        }
        log.info("addApprovalsParams--" + addApprovalsParams);
        Boolean aBoolean = tpApproveFlowService.addSubNodes(addApprovalsParams, 1, 1, new Date());
        Assert.notTrue(aBoolean, "新增操作节点时失败");
        List<TpApproveFlow> flows = new ArrayList<>();
        for (int i = 0; i < applicationNumList.size(); i++) {
            String resId = resIdList.get(i);
            TpApproveFlowConfig config = configMap.get(resId);
            int deptId = config.getAuditDepartmentId();
            int roleId = config.getAuditRoleId();
            TpApproveFlow tpApproveFlow = new TpApproveFlow();
            tpApproveFlow.setApplyId(applicationNumList.get(i))
                    .setApprovalDeptId(deptId)
                    .setApprovalRoleId(roleId)
                    .setResId(resId)
                    .setResult(1)
                    .setFlowAvailable(1)
                    .setCurrentFlowLink(config.getCurrentFlowLink())
                    .setNextFlowLink(config.getNextFlowNode())
                    .setCreateTime(new Date())
                    .setCurrentFlowLink(1)
                    .setUserId(userIdList.get(i));
            flows.add(tpApproveFlow);
        }
        Boolean tafsSave = tpApproveFlowService.insertMany(flows);
        if (!tafsSave) {
            log.info("多条中,存在生成第一节点失败的数据!");
            return -3;
        }
        log.info("多条申请成功");
        return 1;
    }

    /**
     * 我的订阅申请表单(撤回)
     *
     * @param applicationNum 撤回的订单号
     * @param userId         当前操作人员id
     * @param date           时间
     * @param type           操作类型(0-无需要新增操作节点  1-需新增操作节点)
     * @return
     */
    @Override
    public Boolean withdraw(String applicationNum, Integer userId, Date date, Integer type) throws BizException {
        if (applicationNum == null || userId == null || type == null) {
            log.info("withdraw传入值有问题");
            return false;
        }
        // ------------撤回TpOrder && 撤回TpApprovaFlow----------------------
        tpOrderService.withdrawOrderAndFlows(applicationNum, date, userId);
        TpOrder order = tpOrderService.getOne(Wrappers.<TpOrder>lambdaQuery().eq(TpOrder::getApplicationNum, applicationNum)
                .eq(TpOrder::getOrderAvailable, 1));
        // 新增操作节点
        if (type == 1) {
            Boolean aBoolean = tpApproveFlowService.addSubNode(applicationNum, userId, 3, date, order.getResId());
            Assert.notTrue(aBoolean, "取消时,新增操作节点失败!");
        }
        log.info("强制退回成功");
        return true;
    }

    /**
     * 订阅审批表单(多条件)
     *
     * @param deptIdList   登陆人的部门id集
     * @param roldIdList   登陆人的角色id集
     * @param result       1未审批  2审批   根据流程节点状态查询
     * @param applyNum     根据订单号模糊查询
     * @param gsOrderState 订单的状态
     * @param prefix       资源id前缀
     * @return
     */
    @Override
    public List<TpOrder> selectTpOrderApprovalByCondition(List<Integer> deptIdList, List<Integer> roldIdList,
                                                          Integer result, String applyNum, Integer gsOrderState, String prefix) {
        // 查询出需要本角色审批的TpOrder
        LambdaQueryWrapper<TpApproveFlow> tafWra = new LambdaQueryWrapper<>();
        if (result == null || result.equals("")) {
            // 查询出需要本角色审批的TpOrder
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix);
        } else if (result == 1) {
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .eq(TpApproveFlow::getResult, result)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix);
        } else if (result == 2) {
            List<Integer> resultList = new ArrayList<>();
            resultList.add(2);
            resultList.add(3);
            // 查询出需要本角色审批的TpOrder
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .in(resultList != null, TpApproveFlow::getResult, resultList)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix);
        }

        List<TpApproveFlow> tpApproveFlowList = tpApproveFlowService.list(tafWra);
        // 获取通过节点信息查询的订单号
        List<String> applyIdList = new ArrayList<>();
        for (int i = 0; i < tpApproveFlowList.size(); i++) {
            applyIdList.add(tpApproveFlowList.get(i).getApplyId());
        }
        if (applyIdList.size() == 0) {
            return new ArrayList<>();
            // return new Page<TpOrder>().setSize(page.getSize()).setCurrent(page.getCurrent()).setRecords(new ArrayList<>());
        }
        // 拿到订单号以后再通过订单状态查询相应的订单信息
        LambdaQueryWrapper<TpOrder> lqwto = new LambdaQueryWrapper<>();
        lqwto.eq(TpOrder::getOrderAvailable, 1)
                .eq(gsOrderState != null, TpOrder::getGsOrderState, gsOrderState)
                .in(TpOrder::getApplicationNum, applyIdList);
        List<TpOrder> list = tpOrderService.list(lqwto);
        // IPage<TpOrder> pageData = tpOrderService.page(page, lqwto);
        return list;
    }

    /**
     * 审批列表(不分页)
     *
     * @param deptIdList 登陆人的部门id集
     * @param roldIdList 登陆人的角色id集
     * @param result     1未审批  2审批   根据流程节点状态查询
     * @param prefix     资源id前缀
     * @return
     */
    @Override
    public List<String> selectMyApprovalTable(List<Integer> deptIdList, List<Integer> roldIdList, Integer result, String prefix) {
        // 查询出需要本角色审批的TpOrder
        LambdaQueryWrapper<TpApproveFlow> tafWra = new LambdaQueryWrapper<>();
        if (result == null || result.equals("")) {
            // 查询出需要本角色审批的TpOrder
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix);
        } else if (result == 1) {
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .eq(TpApproveFlow::getResult, result)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix);
        } else if (result == 2) {
            List<Integer> resultList = new ArrayList<>();
            resultList.add(2);
            resultList.add(3);
            // 查询出需要本角色审批的TpOrder
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .in(resultList != null, TpApproveFlow::getResult, resultList)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix);
        }
        // 获取通过节点信息查询的订单号
        List<String> applyNums = tpApproveFlowService.list(tafWra).stream().map(TpApproveFlow::getApplyId).collect(Collectors.toList());
        return applyNums;
    }

    /**
     * 审批
     *
     * @param tpApproveFlow ApplyId[订单号]；Result[审批结果]；UserId[当前操作人]；ResId[资源id]
     * @param deptIdList    当前操作人员部门id列表
     * @param roleIdList    当前操作人员角色id列表
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateNodeApprovalResults(TpApproveFlow tpApproveFlow, List<Integer> deptIdList, List<Integer> roleIdList) throws Exception {
        Assert.isNull(tpApproveFlow.getApplyId(), "数据异常！");
        String applyNum = tpApproveFlow.getApplyId();
        Date date = new Date();
        // 修改前先检查当前节点有没有被别人审批
        TpApproveFlow oneFlow = tpApproveFlowService.getOne(Wrappers.<TpApproveFlow>lambdaQuery()
                .eq(TpApproveFlow::getApplyId, applyNum).eq(TpApproveFlow::getFlowAvailable, 1)
                .in(TpApproveFlow::getApprovalDeptId, deptIdList).in(TpApproveFlow::getApprovalRoleId, roleIdList));
        // 判断空指针
        Assert.isTrue(oneFlow == null, "审批数据为空");
        int oneResult = oneFlow.getResult();
        // 修改时如果已经被审批，则直接返回
        Assert.isTrue(oneResult != 1, "当前流程节点已被其他人员审批");
        // 如果没有被审批，拿到当前人员的审批结果，拿到审批人id
        int result = tpApproveFlow.getResult();
        int userId = tpApproveFlow.getUserId();

        // 进行审批，修改当前节点的审批状态
        oneFlow.setResult(result).setAuditOpinion(tpApproveFlow.getAuditOpinion()).setModifyTime(date).setModifyUser(userId);
        Boolean res = tpApproveFlowService.updateById(oneFlow);
        Assert.notTrue(res, "修改我的审批节点状态时出错！");
        if (result == 3) {
            // 增加版本号
            int editionMax = tpApproveFlowService.selectMaxEdition(applyNum);
            LambdaUpdateWrapper<TpApproveFlow> updateTpApproveFlow = new LambdaUpdateWrapper<>();
            updateTpApproveFlow.eq(TpApproveFlow::getApplyId, applyNum)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .set(TpApproveFlow::getEdition, editionMax + 1);
            Boolean utaf = tpApproveFlowService.update(updateTpApproveFlow);
            if (!utaf) {
                log.info("新增版本号出错");
                return -1;
            }
            LambdaUpdateWrapper<TpOrder> updateTpOrder = new LambdaUpdateWrapper<>();
            updateTpOrder.eq(TpOrder::getApplicationNum, applyNum)
                    .eq(TpOrder::getOrderAvailable, 1)
                    .set(TpOrder::getGsOrderState, 7);
            Boolean up = tpOrderService.update(updateTpOrder);
            if (!up) {
                log.info("驳回失败");
                return -1;
            }
            // 发送状态给mq
            Boolean mqBoolean = tpOrderService.sendMq(applyNum, oneFlow.getResId());
            Assert.notTrue(mqBoolean, "发送消息失败！");
            log.info("驳回成功，该订单审批完成！");
            return 1;
            // 如果审批通过
        } else {
            TpOrder order = tpOrderService.getOne(Wrappers.<TpOrder>lambdaQuery()
                    .eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1));
            if (null == order.getConfigHisNum()) {
                Integer integer = tpApproveFlowService.updateResultByConfig(applyNum, oneFlow, date, userId);
                Assert.isTrue(integer != 1, "审批出错！");
            }
            if (order.getConfigHisNum() != null) {
                Integer configHisNum = order.getConfigHisNum();
                Integer integer = tpApproveFlowService.updateResultByOldConfig(applyNum, oneFlow, date, userId, configHisNum);
                Assert.isTrue(integer != 1, "审批出错！");
            }
        }
        return 1;
    }

    /**
     * ip审批
     *
     * @param tpApproveFlow ApplyId[订单号]；Result[审批结果]；UserId[当前操作人]；ResId[资源id]
     * @param deptIdList    当前操作人员部门id列表
     * @param roleIdList    当前操作人员角色id列表
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateIpNodeApprovalResults(TpApproveFlow tpApproveFlow, List<Integer> deptIdList, List<Integer> roleIdList,Integer deptBaseId, Integer roleBaseId) throws Exception {
        Assert.isNull(tpApproveFlow.getApplyId(), "数据异常！");
        String applyNum = tpApproveFlow.getApplyId();
        Date date = new Date();
        // 修改前先检查当前节点有没有被别人审批
        TpApproveFlow oneFlow = tpApproveFlowService.getOne(Wrappers.<TpApproveFlow>lambdaQuery()
                .eq(TpApproveFlow::getApplyId, applyNum).eq(TpApproveFlow::getFlowAvailable, 1)
                .in(TpApproveFlow::getApprovalDeptId, deptIdList).in(TpApproveFlow::getApprovalRoleId, roleIdList));
        // 判断空指针
        Assert.isTrue(oneFlow == null, "审批数据为空");
        int oneResult = oneFlow.getResult();
        // 修改时如果已经被审批，则直接返回
        Assert.isTrue(oneResult != 1, "当前流程节点已被其他人员审批");
        // 如果没有被审批，拿到当前人员的审批结果，拿到审批人id
        int result = tpApproveFlow.getResult();
        int userId = tpApproveFlow.getUserId();

        // 进行审批，修改当前节点的审批状态
        oneFlow.setResult(result).setAuditOpinion(tpApproveFlow.getAuditOpinion()).setModifyTime(date).setModifyUser(userId);
        Boolean res = tpApproveFlowService.updateById(oneFlow);
        Assert.notTrue(res, "修改我的审批节点状态时出错！");
        if (result == 3) {
            // 增加版本号
            int editionMax = tpApproveFlowService.selectMaxEdition(applyNum);
            LambdaUpdateWrapper<TpApproveFlow> updateTpApproveFlow = new LambdaUpdateWrapper<>();
            updateTpApproveFlow.eq(TpApproveFlow::getApplyId, applyNum)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .set(TpApproveFlow::getEdition, editionMax + 1);
            Boolean utaf = tpApproveFlowService.update(updateTpApproveFlow);
            if (!utaf) {
                log.info("新增版本号出错");
                return -1;
            }
            LambdaUpdateWrapper<TpOrder> updateTpOrder = new LambdaUpdateWrapper<>();
            updateTpOrder.eq(TpOrder::getApplicationNum, applyNum)
                    .eq(TpOrder::getOrderAvailable, 1)
                    .set(TpOrder::getGsOrderState, 7);
            Boolean up = tpOrderService.update(updateTpOrder);
            if (!up) {
                log.info("驳回失败");
                return -1;
            }
            // 发送状态给mq
            Boolean mqBoolean = tpOrderService.sendMq(applyNum, oneFlow.getResId());
            Assert.notTrue(mqBoolean, "发送消息失败！");
            log.info("驳回成功，该订单审批完成！");
            return 1;
            // 如果审批通过
        } else {
            TpOrder order = tpOrderService.getOne(Wrappers.<TpOrder>lambdaQuery()
                    .eq(TpOrder::getApplicationNum, applyNum).eq(TpOrder::getOrderAvailable, 1));
            if (null == order.getConfigHisNum()) {
                Integer integer = tpApproveFlowService.updateResultNotByConfig(applyNum, oneFlow, date, userId,deptBaseId,roleBaseId);
                Assert.isTrue(integer != 1, "审批出错！");
            }
            if (order.getConfigHisNum() != null) {
                Integer configHisNum = order.getConfigHisNum();
                Integer integer = tpApproveFlowService.updateResultByOldConfig(applyNum, oneFlow, date, userId, configHisNum);
                Assert.isTrue(integer != 1, "审批出错！");
            }
        }
        return 1;
    }

    /**
     * 根据部门角色和平台前缀查询资源id
     *
     * @param deptIdList 部门id集合
     * @param roleIdList 角色is集合
     * @param prefix     资源id前缀
     * @return
     * @throws BizException
     */
    @Override
    public List<String> selectByDeptAndRole(List<Integer> deptIdList, List<Integer> roleIdList, String prefix) throws BizException {
        Assert.notTrue(!deptIdList.isEmpty() && !roleIdList.isEmpty() && !prefix.isEmpty(), "传入的数据有问题");
        List<TpApproveFlowConfig> listConfig = tpApproveFlowConfigService.list(Wrappers.<TpApproveFlowConfig>lambdaQuery().in(TpApproveFlowConfig::getAuditDepartmentId, deptIdList)
                .in(TpApproveFlowConfig::getAuditRoleId, roleIdList).like(TpApproveFlowConfig::getResId, prefix));
        List<String> collectResId = listConfig.stream().map(TpApproveFlowConfig::getResId).collect(Collectors.toList());
        return collectResId;
    }

    /**
     * 当前审批节点查询
     *
     * @param applyNum   订单号
     * @param deptIdList 登陆人员部门信息
     * @param roleIdList 登陆人员角色信息
     * @param prefix     平台前缀 E："[资源目录]"
     * @return
     */
    @Override
    public Integer selectCurrentFlowLink(String applyNum, List<Integer> deptIdList, List<Integer> roleIdList, String prefix) throws BizException {
        Assert.isNull(applyNum, "请放入订单号");
        Assert.isNull(deptIdList, "该账号部门信息错误");
        Assert.isNull(roleIdList, "该账号角色信息错误");
        Assert.isNull(prefix, "请放入正确的平台前缀");

        TpApproveFlow oneFlowLink = tpApproveFlowService.getOne(Wrappers.<TpApproveFlow>lambdaQuery().eq(TpApproveFlow::getApplyId, applyNum)
                .in(TpApproveFlow::getApprovalDeptId, deptIdList).in(TpApproveFlow::getApprovalRoleId, roleIdList));
        Integer currentFlowLink = oneFlowLink.getCurrentFlowLink();
        return currentFlowLink;
    }

    /**
     * 批量当前审批节点查询
     *
     * @param applyNumList 订单号
     * @param deptIdList   登陆人员部门信息
     * @param roleIdList   登陆人员角色信息
     * @param prefix       平台前缀 E："[资源目录]"
     * @return
     */
    @Override
    public List<Integer> selectCurrentFlowLinkList(List<String> applyNumList, List<Integer> deptIdList, List<Integer> roleIdList, String prefix) throws BizException {
        Assert.isNull(applyNumList, "请放入订单号");
        Assert.isNull(deptIdList, "该账号部门信息错误");
        Assert.isNull(roleIdList, "该账号角色信息错误");
        Assert.isNull(prefix, "请放入正确的平台前缀");

        List<TpApproveFlow> oneFlowLinks = tpApproveFlowService.list(Wrappers.<TpApproveFlow>lambdaQuery().in(TpApproveFlow::getApplyId, applyNumList)
                .in(TpApproveFlow::getApprovalDeptId, deptIdList).in(TpApproveFlow::getApprovalRoleId, roleIdList));
        List<Integer> currentFlowLinks = oneFlowLinks.stream().map(TpApproveFlow::getCurrentFlowLink).collect(Collectors.toList());
        return currentFlowLinks;
    }

    /**
     * 订阅审批表单(多条件)
     *
     * @param page
     * @param deptIdList   登陆人的部门id集
     * @param roldIdList   登陆人的角色id集
     * @param result       1未审批  2审批   根据流程节点状态查询
     * @param applyNums    根据订单号模糊查询
     * @param gsOrderState 订单的状态
     * @param prefix       资源id前缀
     * @return
     */
    @Override
    public IPage<TpOrder> selectTpOrderApprovalToDir(Page<TpOrder> page, List<Integer> deptIdList, List<Integer> roldIdList,
                                                     Integer result, List<String> applyNums, Integer gsOrderState, String prefix) {
        // 查询出需要本角色审批的TpOrder
        LambdaQueryWrapper<TpApproveFlow> selectApprovalFlow = new LambdaQueryWrapper<>();
        if (result == null || result.equals("")) {
            // 查询出需要本角色审批的TpOrder
            selectApprovalFlow.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix)
                    .in(!applyNums.isEmpty(), TpApproveFlow::getApplyId, applyNums);
        } else if (result == 1) {
            selectApprovalFlow.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .eq(TpApproveFlow::getResult, result)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix)
                    .in(!applyNums.isEmpty(), TpApproveFlow::getApplyId, applyNums);
        } else if (result == 2) {
            List<Integer> resultList = new ArrayList<>();
            resultList.add(2);
            resultList.add(3);
            // 查询出需要本角色审批的TpOrder
            selectApprovalFlow.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .in(resultList != null, TpApproveFlow::getResult, resultList)
                    .eq(TpApproveFlow::getFlowAvailable, 1)
                    .like(StringUtil.isNotBlank(prefix), TpApproveFlow::getResId, prefix)
                    .in(!applyNums.isEmpty(), TpApproveFlow::getApplyId, applyNums);
            log.info("本次查询已审批订单");
        }

        List<TpApproveFlow> tpApproveFlowList = tpApproveFlowService.list(selectApprovalFlow);
        if (tpApproveFlowList.isEmpty()) {
            return new Page<TpOrder>().setSize(page.getSize()).setCurrent(page.getCurrent()).setRecords(new ArrayList<>());
        }
        // 获取通过节点信息查询的订单号
        List<String> applyIdList = tpApproveFlowList.stream().map(TpApproveFlow::getApplyId).collect(Collectors.toList());

        // 拿到订单号以后再通过订单状态查询相应的订单信息
        LambdaQueryWrapper<TpOrder> lqwto = new LambdaQueryWrapper<>();
        lqwto.eq(TpOrder::getOrderAvailable, 1)
                .eq(gsOrderState != null, TpOrder::getGsOrderState, gsOrderState)
                .in(TpOrder::getApplicationNum, applyIdList);
        IPage<TpOrder> pageOrder = tpOrderService.page(page, lqwto);
        return pageOrder;
    }

    /**
     * 事项录入订阅审批表单
     *
     * @param deptIdList 当前操作人员部门id列表
     * @param roldIdList 当前操作人员角色id列表
     * @param result     当前节点审批结果
     * @return
     */
    @Override
    public List<TpOrder> selectTpOrderApprovalToTMatter(List<Integer> deptIdList, List<Integer> roldIdList, Integer result) {
        // 查询出需要本角色审批的TpOrder
        LambdaQueryWrapper<TpApproveFlow> tafWra = new LambdaQueryWrapper<>();
        if (result == null) {
            // 查询出需要本角色审批的TpOrder
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .eq(TpApproveFlow::getFlowAvailable, 1);
        } else if (result == 1) {
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .eq(TpApproveFlow::getResult, result)
                    .eq(TpApproveFlow::getFlowAvailable, 1);
        } else if (result == 2) {
            List<Integer> resultList = new ArrayList<>();
            resultList.add(2);
            resultList.add(3);
            // 查询出需要本角色审批的TpOrder
            tafWra.in(TpApproveFlow::getApprovalDeptId, deptIdList)
                    .in(TpApproveFlow::getApprovalRoleId, roldIdList)
                    // 根据流程节点状态查询
                    .in(resultList != null, TpApproveFlow::getResult, resultList)
                    .eq(TpApproveFlow::getFlowAvailable, 1);
        }

        List<TpApproveFlow> tpApproveFlowList = tpApproveFlowService.list(tafWra);
        // 获取通过节点信息查询的订单号
        List<String> applyIdList = new ArrayList<>();
        ;
        for (int i = 0; i < tpApproveFlowList.size(); i++) {
            applyIdList.add(tpApproveFlowList.get(i).getApplyId());
        }

        if (applyIdList.size() == 0) {
            return new ArrayList<>();
        }
        // 拿到订单号以后再通过订单状态查询相应的订单信息
        LambdaQueryWrapper<TpOrder> lqwto = new LambdaQueryWrapper<>();
        lqwto.eq(TpOrder::getOrderAvailable, 1)
                .in(TpOrder::getApplicationNum, applyIdList)
                .orderByDesc(TpOrder::getApplyTime);
        List<TpOrder> result1 = tpOrderService.list(lqwto);
        return result1;
    }

    /**
     * 事项录入查询节点信息
     *
     * @param applicationNum 数据的订单号
     * @return
     */
    @Override
    public List<TpApproveFlow> selectApprovalFlowByTMatterResId(String applicationNum) {
        LambdaQueryWrapper<TpApproveFlow> lqwtaf = new LambdaQueryWrapper<TpApproveFlow>();
        lqwtaf.eq(TpApproveFlow::getApplyId, applicationNum)
                .eq(TpApproveFlow::getFlowAvailable, 1)
                .orderByAsc(TpApproveFlow::getCreateTime);
        List<TpApproveFlow> tpApproveFlow = tpApproveFlowService.list(lqwtaf);
        return tpApproveFlow;
    }

    /**
     * 事项录入申请（新增未提交申请到order）
     *
     * @param id        主键id
     * @param resId     资源id
     * @param userId    人员id
     * @param randomNum 订单号
     * @return Boolean
     */
    @Override
    public Boolean insertRcToOrder(Integer id, String resId, Integer userId, String randomNum) throws BizException {
        Date date = new Date();
        // 先检查该数据是否已经被提交审核
        LambdaQueryWrapper<TpApproveFlow> lqwtaf = new LambdaQueryWrapper<>();
        lqwtaf.eq(TpApproveFlow::getResId, resId)
                .eq(TpApproveFlow::getFlowAvailable, 1);
        TpApproveFlow tpApproveFlow = tpApproveFlowService.getOne(lqwtaf);
        if (tpApproveFlow != null) {
            return false;
        }
        TpOrder tpOrder = new TpOrder();
        tpOrder.setApplicationNum(randomNum)
                .setResId(resId)
                .setApplyTime(date)
                .setResType("事项录入")
                .setOrderAvailable(1)
                .setGsOrderState(1)
                .setOrderAvailable(1);
        Boolean tpoSave = tpOrderService.save(tpOrder);
        if (tpoSave == false) {
            return false;
        }
        Integer updateApprovalNotToYes = updateApprovalNotToYes(randomNum, userId, 1, date);
        if (updateApprovalNotToYes != 1) {
            return false;
        }
        return true;
    }

    /**
     * 资源目录,下架后干涉到流程的发布
     *
     * @param auditDepartmentId
     * @param auditRoleId
     * @param prefix
     * @param rId
     * @return
     * @throws Exception
     */
    @Override
    public Integer lowerShelfRes(List<Integer> auditDepartmentId, List<Integer> auditRoleId, String prefix, Integer rId, Integer moveUser, Date date) throws Exception {
        Assert.isNull(prefix, "传入的数据有问题，请核查！");
        Assert.isNull(rId, "传入的数据有问题，请核查！");
        String resId = prefix + rId;
        List<TpApproveFlow> flows = tpApproveFlowService.list(Wrappers.<TpApproveFlow>lambdaQuery().eq(TpApproveFlow::getFlowAvailable, 1)
                .eq(TpApproveFlow::getResId, resId).isNull(TpApproveFlow::getConfigHisNum));
        if (!flows.isEmpty()) {
            List<TpApproveFlowConfig> configs = tpApproveFlowConfigService.list(Wrappers.<TpApproveFlowConfig>lambdaQuery()
                    .eq(TpApproveFlowConfig::getResId, resId));
            List<TpConfigOld> conOlds = tpConfigOldService.list(Wrappers.<TpConfigOld>lambdaQuery().eq(TpConfigOld::getResId, resId));
            // 新增流程模板的历史数据
            Integer historyMax = 1;
            if (conOlds.isEmpty()) {
                Boolean aBoolean = tpConfigOldService.insertMany(configs, historyMax, moveUser);
                Assert.notTrue(aBoolean, "新增流程模板历史数据出错！");
            } else {
                List<Integer> historyNum = conOlds.stream().map(TpConfigOld::getHistoryNum).collect(Collectors.toList());
                Integer oldMax = Collections.max(historyNum);
                historyMax = oldMax + 1;
                Boolean aBoolean = tpConfigOldService.insertMany(configs, historyMax, moveUser);
                Assert.notTrue(aBoolean, "新增流程模板历史数据出错！");
            }
            // 将正在申请中的订单归属到他的流程模板中
            boolean updateorders = tpOrderService.update(Wrappers.<TpOrder>lambdaUpdate()
                    .eq(TpOrder::getResId, resId).eq(TpOrder::getOrderAvailable, 1)
                    .set(TpOrder::getConfigHisNum, historyMax));
            Assert.notTrue(updateorders, "订单关联流程模板版本失败！");
            boolean updateFlows = tpApproveFlowService.update(Wrappers.<TpApproveFlow>lambdaUpdate()
                    .eq(TpApproveFlow::getResId, resId).eq(TpApproveFlow::getFlowAvailable, 1)
                    .set(TpApproveFlow::getConfigHisNum, historyMax));
            Assert.notTrue(updateFlows, "流程关联流程模板版本失败！");
            // 配置流程模板
            String insertApproval = insertApproval(auditDepartmentId, auditRoleId, prefix, rId.toString());
            Assert.notTrue(insertApproval.equals("流程生成成功"), "新流程生成失败！");
        } else {
            // 配置流程模板
            String insertApproval = insertApproval(auditDepartmentId, auditRoleId, prefix, rId.toString());
            Assert.notTrue(insertApproval.equals("流程生成成功"), "新流程生成失败！");
        }
        return 1;
    }


    /**
     * ip修改申请单生成入口
     *
     * @param list(放入[order_item_no,res_id,user_id]) order_item_no订单号, res_id:E("[查询平台]22"), user_id人员id
     * @return Integer
     */
    @Override
    public Integer ipUpdateOrderCreate(List<Map<String, Object>> list) throws BizException {
        // 只能被需要的数据
        Date date = new Date();
        // 一条订单
        if (list.size() == 1) {
            // 获取订单信息
            String orderNo = (String) list.get(0).get("order_item_no");
            String resId = (String) list.get(0).get("res_id");
            Integer resPower = (Integer) list.get(0).get("resPower");
            Integer deptBaseId = (Integer) list.get(0).get("deptBaseId");
            Integer sourceDeptId = (Integer) list.get(0).get("sourceDeptId");
            Integer userId = (Integer) list.get(0).get("user_id");
            Integer approvalUserId = (Integer) list.get(0).get("approvalUserId");
            // 生成订单
            TpOrder tpOrder = new TpOrder();
            tpOrder.setApplicationNum(orderNo)
                    .setResId(resId)
                    .setGsOrderState(3)
                    .setOrderAvailable(1)
                    .setApplyTime(date);
            Boolean tpOrderSave = tpOrderService.save(tpOrder);
            if (!tpOrderSave) {
                return -1;
            }
            // updateApprovalNotToYes(-1该订单数据异常  -2提交失败  -3节点生成失败)
            Integer updateApprovalNotToYes = ipUpdateApprovalNotToYes(orderNo, userId, 1, date, resPower, deptBaseId, sourceDeptId, approvalUserId);
            if (updateApprovalNotToYes == -1) {
                return -1;
            } else if (updateApprovalNotToYes == -2) {
                return -2;
            } else if (updateApprovalNotToYes == -3) {
                return -3;
            }
            // 多条订单
        } else {
            List<String> applicationNumList = new ArrayList<>();
            List<String> resIdList = new ArrayList<>();
            List<Integer> userIdList = new ArrayList<>();
            List<Integer> resPowerList = new ArrayList<>();
            List<Integer> sourceDeptIdList = new ArrayList<>();
            Integer approvalUserId = null;
            Integer deptBaseId = null;
            for (int i = 0; i < list.size(); i++) {
                String orderNo = (String) list.get(i).get("order_item_no");
                applicationNumList.add(orderNo);
                String resId = (String) list.get(i).get("res_id");
                resIdList.add(resId);
                Integer userId = (Integer) list.get(i).get("user_id");
                userIdList.add(userId);
                Integer resPower = (Integer) list.get(i).get("resPower");
                resPowerList.add(resPower);
                deptBaseId = (Integer) list.get(i).get("deptBaseId");
                Integer sourceDeptId = (Integer) list.get(i).get("sourceDeptId");
                approvalUserId = (Integer) list.get(i).get("approvalUserId");
                sourceDeptIdList.add(sourceDeptId);
                TpOrder tpOrder = new TpOrder();
                tpOrder.setApplicationNum(orderNo)
                        .setResId(resId)
                        .setGsOrderState(3)
                        .setOrderAvailable(1)
                        .setApplyTime(new Date());
                Boolean tpOrderSava = tpOrderService.save(tpOrder);
                if (!tpOrderSava) {
                    log.info("多条中,存在生成云订错误的情况!");
                    return -1;
                }
            }
            // updateApprovalNotToYesMany(-1多条订单中，存在订单异常  -2存在申请的资源未配置流程! -3多条中,存在生成第一节点失败的数据!)
            Integer updateApprovalNotToYesMany = ipUpdateApprovalNotToYesMany(applicationNumList, resIdList, userIdList, resPowerList, deptBaseId, sourceDeptIdList, approvalUserId);
            if (updateApprovalNotToYesMany == -1) {
                return -1;
            } else if (updateApprovalNotToYesMany == -2) {
                return -2;
            } else if (updateApprovalNotToYesMany == -3) {
                return -3;
            }
        }
        return 1;
    }


    /**
     * ip单条申请
     *
     * @param applicationNum 提交申请时传入申请单号
     * @param userId         提交人的id
     * @return
     */
    @Override
    public Integer ipUpdateApprovalNotToYes(String applicationNum, Integer userId, Integer operType, Date date, Integer resPower, Integer deptBaseId, Integer sourceDeptId, Integer approvalUserId) throws BizException {
        // 查询该订单
        LambdaQueryWrapper<TpOrder> lqwto = new LambdaQueryWrapper<>();
        lqwto.eq(TpOrder::getApplicationNum, applicationNum).eq(TpOrder::getOrderAvailable, 1);
        TpOrder order = tpOrderService.getOne(lqwto);
        if (order == null) {
            log.info("云订单异常");
            return -1;
        }
        String resId = order.getResId();
        if (resPower == 1 || deptBaseId.equals(sourceDeptId)) {
            // 生成操作节点
            Boolean addSubNode = tpApproveFlowService.addSubNode(applicationNum, userId, operType, date, resId);
            Assert.notTrue(addSubNode, "新增提交操作节点时失败");
            // 获得第一审批节点的部门和角色id
            TpApproveFlow tpApproveFlow = new TpApproveFlow();
            tpApproveFlow.setApplyId(applicationNum)
                    .setApprovalDeptId(deptBaseId)
                    .setApprovalRoleId(approvalUserId)
                    .setResId(resId)
                    .setResult(1)
                    .setFlowAvailable(1)
                    .setCreateTime(new Date())
                    .setCurrentFlowLink(1)
                    .setUserId(userId);
            Boolean tafsSave = tpApproveFlowService.save(tpApproveFlow);
            if (!tafsSave) {
                log.info("节点生成失败");
                return -3;
            }
            log.info("提交申请成功，并成功生成第一节点");
            return 1;
        } else if (resPower == 2 && !deptBaseId.equals(sourceDeptId)) {
            // 生成操作节点
            Boolean addSubNode = tpApproveFlowService.addSubNode(applicationNum, userId, operType, date, resId);
            Assert.notTrue(addSubNode, "新增提交操作节点时失败");
            // 获得第一审批节点的部门和角色id
            TpApproveFlow tpApproveFlow = new TpApproveFlow();
            tpApproveFlow.setApplyId(applicationNum)
                    .setApprovalDeptId(sourceDeptId)
                    .setApprovalRoleId(approvalUserId)
                    .setResId(resId)
                    .setResult(1)
                    .setFlowAvailable(1)
                    .setCreateTime(new Date())
                    .setCurrentFlowLink(1)
                    .setNextFlowLink(2)
                    .setUserId(userId);
            Boolean tafsSave = tpApproveFlowService.save(tpApproveFlow);
            if (!tafsSave) {
                log.info("节点生成失败");
                return -3;
            }
            log.info("提交申请成功，并成功生成第一节点");
            return 1;
        } else {
            log.info("获取资源权限失败");
            return -3;
        }
    }

    /**
     * 我的订阅ip申请表单(状态【未提交转提交】多条)
     *
     * @param applicationNumList 提交时传入的申请单号集合
     * @param resIdList          资源id
     * @param userIdList         人员id
     * @return
     */
    @Override
    public Integer ipUpdateApprovalNotToYesMany(List<String> applicationNumList, List<String> resIdList, List<Integer> userIdList, List<Integer> resPowerList, Integer deptBaseId, List<Integer> sourceDeptId, Integer approvalUserId) throws BizException {
        // 查询该订单
        LambdaQueryWrapper<TpOrder> lqwto = new LambdaQueryWrapper<>();
        lqwto.in(TpOrder::getApplicationNum, applicationNumList)
                .eq(TpOrder::getOrderAvailable, 1);
        List<TpOrder> orderList = tpOrderService.list(lqwto);
        for (int i = 0; i < orderList.size(); i++) {
            if (orderList.get(i) == null) {
                log.info("多条订单中，存在订单异常");
                return -1;
            }
        }
        // 生成每个订单的操作节点
        List<AddApprovalsParam> addApprovalsParams = new ArrayList<>();
        for (int i = 0; i < applicationNumList.size(); i++) {
            AddApprovalsParam addApprovalsParam = new AddApprovalsParam();
            addApprovalsParam.setApplyNum(applicationNumList.get(i))
                    .setUserId(userIdList.get(i)).setResId(resIdList.get(i));
            addApprovalsParams.add(addApprovalsParam);
        }
        log.info("addApprovalsParams--" + addApprovalsParams);
        Boolean aBoolean = tpApproveFlowService.addSubNodes(addApprovalsParams, 1, 1, new Date());
        Assert.notTrue(aBoolean, "新增操作节点时失败");
        List<TpApproveFlow> flows = new ArrayList<>();
        for (int i = 0; i < applicationNumList.size(); i++) {
            String resId = resIdList.get(i);
            // 如果订单的资源时公开的或者资源的提供部门是数据资源局，则生成流程无第二节点
            if (resPowerList.get(i) == 1 || sourceDeptId.get(i).equals(deptBaseId)) {
                TpApproveFlow tpApproveFlow = new TpApproveFlow();
                tpApproveFlow.setApplyId(applicationNumList.get(i))
                        .setApprovalDeptId(deptBaseId)
                        .setApprovalRoleId(approvalUserId)
                        .setResId(resId)
                        .setResult(1)
                        .setFlowAvailable(1)
                        .setCurrentFlowLink(1)
                        .setCreateTime(new Date())
                        .setUserId(userIdList.get(i));
                flows.add(tpApproveFlow);
                // 如果订单的资源是受限的且资源提供部门不是数据资源局，则有第二节点
            } else if (resPowerList.get(i) == 2 && !sourceDeptId.get(i).equals(deptBaseId)) {
                TpApproveFlow tpApproveFlow = new TpApproveFlow();
                tpApproveFlow.setApplyId(applicationNumList.get(i))
                        .setApprovalDeptId(sourceDeptId.get(i))
                        .setApprovalRoleId(approvalUserId)
                        .setResId(resId)
                        .setResult(1)
                        .setFlowAvailable(1)
                        .setCurrentFlowLink(1)
                        .setNextFlowLink(2)
                        .setCreateTime(new Date())
                        .setUserId(userIdList.get(i));
                flows.add(tpApproveFlow);
            }
        }
        Boolean tafsSave = tpApproveFlowService.insertMany(flows);
        if (!tafsSave) {
            log.info("多条中,存在生成第一节点失败的数据!");
            return -3;
        }
        log.info("多条申请成功");
        return 1;
    }

    @Override
    public Integer testApi(Map<String, Object> map) throws Exception {
        String decrypt = RSAEncrypt.decrypt((String) map.get("messageEn"), (String) map.get("keyMapOne"));
        if (decrypt.equals(msg)) {
            return 1;
        }
        return 0;
    }
}
